/* eeprom.c */

#include <avr/io.h>
#include "usart.h"
#include "eeprom.h"

unsigned char eeprom_read(unsigned int uiAddress) 
{ 
   /* Wait for completion of previous write */ 
   while(EECR & (1<<EEPE)) {
   }
   
   /* Set up address register */ 
   EEAR = uiAddress; 
   
   /* Start eeprom read by writing EERE */ 
   EECR |= (1<<EERE); 
   
   /* Return data from Data Register */ 
   return EEDR; 
}

void eeprom_write(unsigned int uiAddress, unsigned char ucData) 
{ 
   /* Wait for completion of previous write */ 
   while(EECR & (1<<EEPE)) 
      ; 
   /* Set up address and Data Registers */ 
   EEAR = uiAddress; 
   EEDR = ucData; 
   /* Write logical one to EEMPE */ 
   EECR |= (1<<EEMPE); 
   /* Start eeprom write by setting EEPE */ 
   EECR |= (1<<EEPE); 
}

void eeprom_hexdump_to_usart()
{
   char ascii[17];
   
   ascii[8] = 0x00;

   unsigned char n = 0;
   
   for (unsigned short offset = 0; offset < 512; offset++)
   {
      unsigned char c = eeprom_read(offset);

      if (n == 0) {
         usart_tx_hex((offset >> 8) & 0x00ff);
         usart_tx_hex((offset >> 0) & 0x00ff);
         usart_tx(' ');
         usart_tx(' ');
      }

      if (c >= 32 && c <= 126) {
         ascii[n] = c;
      } else {
         ascii[n] = '.';
      }
      
      usart_tx_hex(c);
      usart_tx(' ');
      
      n++;
      
      if (n == 16) {
         usart_tx(' ');
         usart_tx('|');
         usart_tx_string(ascii);
         usart_tx('|');
         usart_tx('\r');
         usart_tx('\n');
         n = 0;
      }
   }
   
   if (n != 0) {
      while (n != 16) {
         ascii[n] = ' ';
         usart_tx(' ');
         usart_tx(' ');
         usart_tx(' ');
         n++;
      }
      usart_tx(' ');
      usart_tx('|');
      usart_tx_string(ascii);
      usart_tx('|');
      usart_tx('\r');
      usart_tx('\n');
   }   
}
